<template>
  <view class="container">
    <button @click="handleGetCoupon">领取优惠券</button>
    <view v-if="showAuthModal" class="auth-modal">
      <button open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">授权手机号</button>
    </view>
  </view>
</template>

<script>
import { mapState, mapActions } from "pinia";
import { useAppStore } from "@/store";
import Taro from "@tarojs/taro";

export default {
  data() {
    return {
      showAuthModal: false,
    };
  },
  computed: {
    ...mapState(useAppStore, ["currentUser", "phoneNumber"]),
  },
  methods: {
    ...mapActions(useAppStore, ["setPhoneNumber"]),
    handleGetCoupon() {
      if (!this.phoneNumber) {
        this.showAuthModal = true;
      } else {
        // 用户已经授权手机号，可以领取优惠券
        this.getCoupon();
      }
    },
    handleGetPhoneNumber(event) {
      if (event.detail.errMsg === "getPhoneNumber:ok") {
        // 处理手机号授权成功
        const phoneNumber = event.detail.phoneNumber; // 获取手机号（示例，实际中你需要解密数据）
        this.setPhoneNumber(phoneNumber);
        Taro.setStorageSync("phoneNumber", phoneNumber); // 将手机号存储在本地存储
        this.showAuthModal = false;
        this.getCoupon();
      } else {
        // 用户拒绝授权
        Taro.showToast({
          title: "需要手机号授权才能领取优惠券",
          icon: "none",
        });
      }
    },
    getCoupon() {
      // 实现领取优惠券的逻辑
      Taro.showToast({
        title: "优惠券领取成功",
        icon: "success",
      });
    },
    checkLocalPhoneNumber() {
      const phoneNumber = Taro.getStorageSync("phoneNumber");
      if (phoneNumber) {
        this.setPhoneNumber(phoneNumber);
      }
    },
  },
  created() {
    this.checkLocalPhoneNumber();
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>
